﻿using System;
using System.Windows;
using ImageControl.Common;
using ImageControl.Models;

namespace ImageControl.ViewModels.Handlers
{
    public class RotateHandler : HandlerViewModel
    {
        const double FullCircleDegrees = 360;
        const double RadiansToAngles = FullCircleDegrees / (2 * Math.PI);
        

        public RotateHandler(AdornerViewModel adorner)
            : base(adorner)
        {
        }

        public override void HandleMove(Point coordinate)
        {
            Point rotatePoint = this.Adorner.GetRotatedCoordinateFromDocumentPoint(coordinate);
            Point center = this.Adorner.GetRotatedCoordinateFromDocumentPoint(this.Adorner.ImageModel.Center);

            Point rotateVector = rotatePoint.Minus(center);
            if (!rotateVector.IsZero())
            {
                double flippingMultiplier = this.Adorner.ImageModel.HasFlippingY ? -1 : 1;
                Point baseVector = new Point(0, -1 * flippingMultiplier);
                Point unitVector = rotateVector.UnitVector();
                double deltaAngle = flippingMultiplier * Math.Acos(unitVector.MultiplyBy(baseVector)) * RadiansToAngles;
                if (rotatePoint.X < center.X)
                {
                    deltaAngle = FullCircleDegrees - deltaAngle;
                }

                double rotation = (this.Adorner.ImageModel.Rotation + deltaAngle) % FullCircleDegrees;

                this.Adorner.ImageModel = new ImageModel(this.Adorner.ImageModel.OrientedWidth, this.Adorner.ImageModel.OrientedHeight, rotation, this.Adorner.ImageModel.ImageTopLeft);
            }     
        }
    }
}